﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Text;
using GiveAQuiz.Common.Mvvm;

namespace GiveAQuiz.Questions
{
  public partial class MultipleChoiceAnswerControl : UserControl
  {
    public MultipleChoiceAnswerControl()
    {
      InitializeComponent();

      Loaded += new RoutedEventHandler(MultipleChoiceAnswerControl_Loaded);

      this.AddHandler(UIElement.KeyUpEvent, new KeyEventHandler(MultipleChoiceAnswerControl_KeyUp), true);
    }

    void MultipleChoiceAnswerControl_KeyUp(object sender, KeyEventArgs args)
    {
      if (args.Key >= Key.D1 && args.Key <= Key.D9)
      {
        var itemNumber = (int)args.Key - (int)Key.D1;
        CommandHelper.ExecuteCommand(DataContext, "PickAnswerCommand", itemNumber);
      }
    }

    // Had to handle this manually since the data binding to the XAML element does not work as expected
    void MultipleChoiceAnswerControl_Loaded(object sender, RoutedEventArgs e)
    {
      MultipleChoiceQuestionType qType = this.DataContext as MultipleChoiceQuestionType;
      if (qType != null)
      {
        var builder = new StringBuilder();
        string[] paragraphs = qType.QuestionText.Split(new string[] {@"\r\n"}, StringSplitOptions.None);
        foreach (var p in paragraphs)
        {
          Regex ex = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");
          builder.AppendFormat("<Paragraph >{0}</Paragraph>", ex.Replace(qType.QuestionText, m =>
          {
            return string.Format("<Hyperlink NavigateUri=\"{0}\" TargetName=\"_blank\">{0}</Hyperlink>", m.Value);
          }));
        }
        question.Xaml = string.Format(template, builder.ToString());
      }
    }


    // Need the wrap the whole thing into a Section to make this work.
    const string template = @"<Section xml:space=""preserve"" HasTrailingParagraphBreakOnPaste=""False"" xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">{0}</Section>";

    private void RadioButton_Checked(object sender, RoutedEventArgs e)
    {
      var type = DataContext as MultipleChoiceQuestionType;
      var button = (RadioButton)sender;
      var item = button.DataContext as MultipleChoiceQuestionItem;
      if (type != null && item != null)
      {
        foreach (var answer in type.Answers)
        {
          answer.IsCorrectChoice = (item == answer);
        }
      }
    }

  }
}
